import 'package:hive/hive.dart';

part 'task_model.g.dart';

@HiveType(typeId: 0)
class TaskModel extends HiveObject {
  @HiveField(0)
  String id;

  @HiveField(1)
  String name;

  @HiveField(2)
  DateTime startDate;

  @HiveField(3)
  DateTime endDate;

  @HiveField(4)
  String notes;

  @HiveField(5)
  bool reminderEnabled;

  @HiveField(6)
  List<DateTime> completedDates;

  @HiveField(7)
  DateTime createdAt;

  @HiveField(8)
  DateTime updatedAt;

  TaskModel({
    required this.id,
    required this.name,
    required this.startDate,
    required this.endDate,
    this.notes = '',
    this.reminderEnabled = false,
    List<DateTime>? completedDates,
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : completedDates = completedDates ?? [],
        createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  String get status {
    final now = DateTime.now();
    if (now.isBefore(startDate)) {
      return 'notStarted';
    } else if (now.isAfter(endDate)) {
      return 'completed';
    } else {
      return 'ongoing';
    }
  }

  String get progress {
    final totalDays = endDate.difference(startDate).inDays + 1;
    final completedDays = completedDates.length;
    return '$completedDays/$totalDays';
  }

  bool isTodayCompleted(DateTime date) {
    final dateOnly = DateTime(date.year, date.month, date.day);
    return completedDates.any((completedDate) =>
        completedDate.year == dateOnly.year &&
        completedDate.month == dateOnly.month &&
        completedDate.day == dateOnly.day);
  }

  void toggleTodayCompletion(DateTime date) {
    final dateOnly = DateTime(date.year, date.month, date.day);

    if (isTodayCompleted(date)) {
      completedDates.removeWhere((completedDate) =>
          completedDate.year == dateOnly.year &&
          completedDate.month == dateOnly.month &&
          completedDate.day == dateOnly.day);
    } else {
      completedDates.add(dateOnly);
    }

    updatedAt = DateTime.now();
  }

  /// 创建一个空的任务实例
  static TaskModel empty() {
    return TaskModel(
      id: '',
      name: '',
      startDate: DateTime.now(),
      endDate: DateTime.now(),
    );
  }
}
